package com.foyekoo.project001.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.foyekoo.project001.config.Config;
import com.foyekoo.project001.config.ReqData;
import com.foyekoo.project001.utils.ReadThread;
import com.foyekoo.project001.utils.WriteThread;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

public class UsbService extends Service {

    private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

    public static final String ACTION_DATA_RECEIVE = "com.usb.demo.ACTION_DATA_RECEIVE";

    /**
     * manbager对象
     */
    private UsbManager manager;

    /**
     * usb设备
     */
    private UsbDevice device = null;
    /**
     * usb接口对象
     */
    private UsbInterface usbInterface = null;
    /**
     * usb点对象
     */
    private UsbEndpoint[][] endpoint = new UsbEndpoint[5][5];

    private UsbDeviceConnection connection = null;

    /**
     * 请求的队列
     */
    public static LinkedBlockingQueue<ReqData> reqData = new LinkedBlockingQueue<>();

    public static  WriteThread writeThread;

    public static  ReadThread readThread;



    UsbInterface[] usbinterface = null;//usb接口对象
    /**
     * id
     */
    private int myVid = 1155 ,myPid = 22356;

    @Override
    public void onDestroy() {
        super.onDestroy();
    if (device != null) {

    }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        init();

        return super.onStartCommand(intent, flags, startId);

    }



    private void init(){

        if (manager == null) {
            manager = (UsbManager)getSystemService(Context.USB_SERVICE);
            HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
            Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
            while (deviceIterator.hasNext()) { //遍历ID和PID 是否相同 如果是 那么这个设备就是你的
                device = deviceIterator.next();
                if (device.getVendorId() == myVid && device.getProductId() == myPid) {
                    break;
                }
            }

            if (device != null && device.getVendorId() == myVid && device.getProductId() == myPid) {
                //找到设备了 不处理
            } else {
                //没有设备

            }

            //申请USB权限
            requestPermission();
            //寻找USB设备
            findUsbInterface();

            //连接设备
           boolean result =  connectDevice();
            textString += "连接成功";
           if (result) {
               //开启线程

               textString += "打开读写线程";
           }

            openThread();

            registerReceiver(receiveUseWriteData,new IntentFilter(ACTION_DATA_RECEIVE));
            broadcastSend(Config.ACTION_USB_CONNECT, textString);

        }
    }

    private void openThread(){
        if (writeThread == null){
            writeThread = new WriteThread();
            writeThread.setConnection(connection,endpoint);
            writeThread.start();
        }

        if (readThread == null) {
            readThread = new ReadThread() ;
            readThread.setConnection(connection,endpoint);
            readThread.start();
        }


    }

    private boolean connectDevice(){
        if(connection != null) {
            connection.close();
        }

        connection = manager.openDevice(device);
        if (connection == null) {//连接不上
            //TODO
            return false;
        }
        connection.claimInterface(usbinterface[1], true);
        return true;

    }

    private String textString = "";

    private void findUsbInterface(){
        usbinterface = new UsbInterface[device.getInterfaceCount()];
        for (int i = 0; i < device.getInterfaceCount(); i++) {
            usbinterface[i] = device.getInterface(i);
            textString =
                    "\n接口" + i + "的端点数为：" + usbinterface[i].getEndpointCount();
            for (int j = 0; j < usbinterface[i].getEndpointCount(); j++) {
                endpoint[i][j] = usbinterface[i].getEndpoint(j);
                if (endpoint[i][j].getDirection() == 0) {
                  textString += ""
                            + "\n端点" + j + "的数据方向为输出";
                } else {
                    textString += ""
                            + "\n端点" + j + "的数据方向为输入";
                }
            }
        }

    }

    //发送广播
    private void broadcastSend(String config, String data) {
        sendBroadcast(new Intent(config).putExtra(config, data));
    }

    private void requestPermission(){
        PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        if (!manager.hasPermission(device))
            manager.requestPermission(device, pi);
        if (manager.hasPermission(device)) {
            textString += "\n拥有访问权限！";
        } else {
            textString += "\n未拥有访问权限！";
        }
    }



    /**
     * 收到用户发的字节数据 放到队列里面
     * 然后 WriteThread就会从队列里面拿--> see WriteThread
     */
    private BroadcastReceiver receiveUseWriteData = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //收到用户过来的写数据

            byte[] byteData = intent.getByteArrayExtra("data");
            Log.d("acthome","---------------");
            ReqData req = new ReqData();
            req.setName("data");
            req.setDatas(byteData);

            try {
                reqData.put(req);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    };



}
